<template>
  <div>
    <van-nav-bar title="购物车" @click-left="onClickLeft" left-text="返回"
        left-arrow></van-nav-bar>
    <div class="cart-title">
      <van-button size="small" type="danger" @click="clearCart" plain>
        清空购物车
      </van-button>
    </div>
    <div class="cart-list">
      <div class="cart-row" v-for="(item,index) in cartInfo" :key="index">
        <div class="cart-image">
          <img :src="item.image" width="100%" alt="">
        </div>
        <div class="cart-text">
          <div class="cart-goods-name">{{item.name}}</div>
          <div class="cart-control">
             <van-stepper v-model="item.count"></van-stepper>
          </div>
        </div>
        <div class="cart-goods-price">
          <div>
            ￥{{item.price|moneyFilter}}
          </div>
          <div>
            x{{item.count}}
          </div>
          <div class="allPrice">
            ￥{{item.price * item.count | moneyFilter}}
          </div>
        </div>
      </div>
    </div>
    <div class="totalMoney">
      商品总价格：￥{{totalMoney|moneyFilter}}
    </div>
  </div>
</template>

<script>
import {toMoney} from '@/filter/moneyFilter.js'
export default {
  data() {
    return {
      cartInfo:[],
      isEmpty:false
    }
  },
  filters:{
    moneyFilter(money){
      return toMoney(money)
    }
  },
  created() {
    this.getCartInfo();
  },
  computed: {
    totalMoney(){
      let allMoney = 0;
      this.cartInfo.forEach((item,index)=>{
        allMoney+=item.price*item.count;
      })
      localStorage.cartInfo = JSON.stringify(this.cartInfo)
      return allMoney
    }
  },
  methods: {
    //得到购物车数据的方法
    getCartInfo(){
      if(localStorage.cartInfo){
        this.cartInfo=JSON.parse(localStorage.cartInfo)
      }
      this.isEmpty=this.cartInfo>0?true:false
    },
    onClickLeft(){
      this.$router.back(-2);
    },
    addGoodsToCart(){
      let cartInfo = localStorage.cartInfo?JSON.parse(localStorage.cartInfo):[]
      let isHaveGoods = cartInfo.find(cart=>cart.good)
    },
    clearCart(){
      localStorage.removeItem('cartInfo')
      this.cartInfo=[]
    }
  },
  components: {

  }
}
</script>

<style scoped>
.cart-title{
  height: 2rem;
  line-height: 2rem;
  background-color: #fff;
  border-bottom: 1px solid #eae7ed;
  padding: 5px;
  text-align: right;
}
.cart-list{
  background-color: #fff;
}
.cart-row{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  padding: .5rem;
  font-size: .85rem;
  border-bottom: 1px solid #eae7ed;
}
.cart-image{
  flex: 6;
}
.cart-text{
  flex: 14;
  padding-left: 10px;
  
}
.cart-goods-name{
  height: 2rem;
  margin-top: .2rem;
}
.cart-control{
  padding-top: 10px;
}
.cart-goods-price{
  color: coral;
  flex:4;
  margin-top: .3rem;
  text-align: right;
}
.allPrice{
  margin-top: .6rem;
  color: black;
}
.totalMoney{
  text-align: right;
  background-color: #fff;
  border-bottom:1px solid #eae7ed;
  padding: .5rem;
  color: #333;
  margin-bottom: 3rem;
}
</style>
